/////////////////////////////////////////////////////////////////////
//
//  MOE Framework (Meta Object Encapsulation Framework)
//
//  Original Author: Wiksy Wang, 2011
//
/////////////////////////////////////////////////////////////////////

#include "RawByteVector.h"

namespace MOE
{

const RawByteVector RawByteVector::gEmptyStr = RawByteVector();

RawByteVector::RawByteVector()
: _length(0)
, _bytes(NULL)
{
}

RawByteVector::RawByteVector(const RawByteVector& other)
{
	_length = other._length;
	if (_length)
	{
		_bytes = new value_type[_length];
		memcpy(_bytes, other._bytes, _length * sizeof(value_type));
	}
	else
	{
		_bytes = NULL;
	}
}

RawByteVector& RawByteVector::operator=(const RawByteVector& other)
{
	if (_length != other._length)
	{
		delete [] _bytes;
		_length = other._length;
		if (_length)
		{
			_bytes = new value_type[_length];
			memcpy(_bytes, other._bytes, _length * sizeof(value_type));
		}
		else
		{
			_bytes = NULL;
		}
	}
	else
	{
		if (_length != 0) memcpy(_bytes, other._bytes, _length * sizeof(value_type));
	}
	return *this;
}

RawByteVector::~RawByteVector()
{
	delete [] _bytes;
}

void RawByteVector::resize(size_t length)
{
	// Special cases first
	if (length == _length)
	{
		return;
	}
	if (length == 0)
	{
		delete [] _bytes;
		_bytes = NULL;
		_length = 0;
		return;
	}

	// Allocate and copy (will truncate if the new length is shorter)
	value_type* newBytes = new value_type[length];
	size_t copySize = std::min(length, _length);
	memcpy(newBytes, _bytes, copySize);

	// Set the new values.
	delete [] _bytes;
	_bytes = newBytes;
	_length = length;
}

}
